package com.kaili.basic.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.kaili.basic.mapper.DeviceMapper;
import com.kaili.basic.pojo.dto.DeviceLocationDto;
import com.kaili.basic.pojo.dto.DeviceSignDTO;
import com.kaili.basic.pojo.dto.DeviceSignLocationDto;
import com.kaili.basic.pojo.entity.DeviceEntity;
import com.kaili.basic.enums.DeviceEunm;
import com.kaili.basic.pojo.entity.DeviceSignEntity;
import com.kaili.basic.enums.DeviceStatusEunm;
import com.kaili.basic.pojo.vo.DeviceSignLocationVo;
import com.kaili.basic.pojo.vo.DeviceSignTrackVo;
import com.kaili.basic.pojo.vo.DeviceSignVO;
import com.kaili.common.response.CommonStatus;
import com.kaili.common.response.ResponseData;
import com.kaili.common.response.RestStatus;
import com.kaili.common.util.LoginDetailUtils;
import com.kaili.common.util.UUIDUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.kaili.basic.service.IDeviceSignService;
import com.kaili.basic.mapper.DeviceSignMapper;

import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
*  service实现类
* @author:zhouyijian
* @Time: 2019-07-24
* @Copyright: ©  杭州凯立通信有限公司 版权所有
* @Warning: 本内容仅限于公司内部传阅,禁止外泄或用于其它商业目的
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class DeviceSignServiceImpl extends ServiceImpl<DeviceSignMapper, DeviceSignEntity>  implements IDeviceSignService {

    @Autowired
    DeviceSignMapper deviceSignMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Page<DeviceSignVO> queryPageListDetail(DeviceSignDTO dto) {
        DeviceEntity device = new DeviceEntity();
        DeviceSignEntity entity = new DeviceSignEntity();
        Page<DeviceSignVO> page = new Page<DeviceSignVO>();
        if(DeviceEunm.IS_SIGN.getCode().equals(dto.getIsSign())){   //已签
            BeanUtils.copyProperties(dto,entity);
            List<DeviceSignVO> result =deviceSignMapper.querySignDetail(entity);
            page.setRecords(result);
        }else if(DeviceEunm.UN_SIGN.getCode().equals(dto.getIsSign())){  //未签
            BeanUtils.copyProperties(dto,device);
            device.setCreateTime(dto.getDateTime()); //用于设备签到详情查询页面
            device.setIsAction(DeviceStatusEunm.DEVICE_ON.getCode());
            List<DeviceSignVO> result =deviceMapper.queryUnSignDetail(device);
            page.setRecords(result);
        }
        return page;
    }

    @Override
    public String doCreateDeviceSign(DeviceSignDTO dto) {
        JSONObject object = new JSONObject();
        Integer employeeId= LoginDetailUtils.getCurrentEmployeeId();
        String token = UUIDUtil.getUUId();
        //验证设备是否登记且启用
        Boolean result =validateDeviceIsExist(dto.getImei());
        if(result){
            DeviceSignEntity entity = new DeviceSignEntity();
            dto.setCreateBy(employeeId);
            dto.setCreateTime(new Date());
            dto.setRdStatus(DeviceStatusEunm.NORMAL.getCode());
            BeanUtils.copyProperties(dto,entity);
            deviceSignMapper.insert(entity);
            redisTemplate.opsForValue().set(dto.getImei(),token,24*60*60*1000);
            //设备在线表

            object.put("token",token);
            return object.toString();
        }
            object.put("token",null);
            return object.toString();
    }


    @Override
    public List<DeviceSignVO> queryListByCondition(DeviceSignDTO dto) {
        DeviceEntity device = new DeviceEntity();
        DeviceSignEntity entity = new DeviceSignEntity();
        List<DeviceSignVO> result =null;
        if(DeviceEunm.IS_SIGN.getCode().equals(dto.getIsSign())){   //已签
            BeanUtils.copyProperties(dto,entity);
            result =deviceSignMapper.querySignDetail(entity);
        }else if(DeviceEunm.UN_SIGN.getCode().equals(dto.getIsSign())){  //未签
            BeanUtils.copyProperties(dto,device);
            device.setCreateTime(dto.getDateTime()); //用于设备签到详情查询页面
            device.setIsAction(DeviceStatusEunm.DEVICE_ON.getCode());
            result =deviceMapper.queryUnSignDetail(device);
        }
        return result;
    }

    @Override
    public List<DeviceSignVO> querySignTotal(DeviceSignDTO dto) {
        DeviceSignEntity entity = new DeviceSignEntity();
        BeanUtils.copyProperties(dto,entity);
        List<DeviceSignVO> result =deviceSignMapper.querySignTotal(entity);
        return result;
    }

    @Override
    public RestStatus updateDeviceSignByImei(DeviceSignDTO dto) {
        DeviceSignEntity entity = new DeviceSignEntity();
        BeanUtils.copyProperties(dto,entity);
        deviceSignMapper.updateById(entity);
        return CommonStatus.UPDATE_OK;
    }

    /**
     * @Desc:  设备位置
     * @author: shenliqiang
     * @Time: 2019/7/29 14:41
     * @param dto
     * @return java.lang.String[][]
     */

    @Override
    public String[][] queryDeviceLocation(DeviceSignLocationDto dto) {
        if(dto.getDate()==null){//参数中无date则默认为当天
            dto.setDate(Calendar.getInstance().getTime());
        }
        String[][] strings ;
        DeviceLocationDto locationDto = new DeviceLocationDto();
        if(dto.getSn()!=null&&dto.getImei()!=null&&dto.getSn().length>0&&dto.getImei().length>0){
            strings = new String[dto.getImei().length][4];
            for(int i = 0;i<dto.getImei().length;i++){
                locationDto.setDate(dto.getDate());
                locationDto.setSn(dto.getSn()[i]);
                locationDto.setImei(dto.getImei()[i]);
                DeviceSignLocationVo vo =  this.deviceSignMapper.queryDeviceLocation(locationDto);
                strings[i] = new String[]{vo.getId().toString(),vo.getImei(),vo.getLongitude(),vo.getLatitude()};
            }
        }else if(dto.getImei()!=null&&dto.getImei().length>0){
            strings = new String[dto.getImei().length][4];
            for(int i = 0;i<dto.getImei().length;i++){
                locationDto.setDate(dto.getDate());
                locationDto.setImei(dto.getImei()[i]);
                DeviceSignLocationVo vo =  this.deviceSignMapper.queryDeviceLocation(locationDto);
                strings[i] = new String[]{vo.getId().toString(),vo.getImei(),vo.getLongitude(),vo.getLatitude()};
            }
        }else{
            strings = new String[dto.getSn().length][4];
            for(int i = 0;i<dto.getSn().length;i++){
                locationDto.setDate(dto.getDate());
                locationDto.setSn(dto.getSn()[i]);
                DeviceSignLocationVo vo =  this.deviceSignMapper.queryDeviceLocation(locationDto);
                strings[i] = new String[]{vo.getId().toString(),vo.getImei(),vo.getLongitude(),vo.getLatitude()};
            }
        }
        return strings;
    }

    /**
     * @Desc:  设备轨迹
     * @author: shenliqiang
     * @Time: 2019/7/29 14:41
     * @param dto
     * @return java.lang.String[][]
     */

    @Override
    public String[][] queryDeviceTrack(DeviceSignLocationDto dto) {
        if(dto.getDate()==null){//参数中无date则默认为当天
            dto.setDate(Calendar.getInstance().getTime());
        }
        List<DeviceSignTrackVo> list = this.deviceSignMapper.queryDeviceTrack(dto);
        String[][] strings = new String[list.size()][2];
        Iterator<DeviceSignTrackVo> iterator = list.iterator();
        int i = 0;
        while (iterator.hasNext()){
            DeviceSignTrackVo vo = iterator.next();
            strings[i] = new String[]{vo.getLongitude(),vo.getLatitude()};
            i++;
        }
        return strings;

    }

        /**
         * @Desc:验证是否允许登录
         * @author:zhouyijian
         * @time: 2019/7/31 16:47
         * @param imei
         * @return: boolean
         */
        private boolean validateDeviceIsExist(String imei) {
            //true:存在false不存在
            Integer employeeId=LoginDetailUtils.getCurrentEmployeeId();//用户id
            Object object =redisTemplate.opsForValue().get(imei);
            DeviceEntity entity =deviceMapper.getIsActionByImei(imei);
            if(entity==null){    //系统中没有记录不允许登录
                return false;
            }
            if(StringUtils.isEmpty(entity.getIsAction())){ //设备未启用不允许登录
                return false;
            }
            if(object!=null){ //设备已登录
                return  false;
            }
        /*if (entity.getOrgId()!=null){
            //绑定到机构的非本机构的不允许登录
            if(orgId.equals(entity.getOrgId())){
                return true;
            }else{
                return false;
            }
        }else if(entity.getUserId()!=null){
            //绑定到个人的非本人工号不允许登录
            if(entity.getUserId().equals(employeeId)){
                return true;
            }else{
                return false;
            }
        }*/
            return true;
        }

}
